import { Button } from "antd";
import { useRef, useState } from "react";

const CameraDemo = () => {
	const videoWidth = 120;
	const videoHeight = 80;
	const videoRef = useRef<HTMLVideoElement | null>(null);
	const mediaStream = useRef<MediaStream | null>(null);
	const [imgSrc, setImgSrc] = useState("");
	const videoChunks = useRef<BlobPart[]>([]);
	const mediaRecorder = useRef<MediaRecorder>();
	const [reviewVideoSrc, setReviewVideoSrc] = useState<string>("");
	const launch = () => {
		window.navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(value => {
			if (!videoRef.current) return;
			mediaStream.current = value;
			videoRef.current.srcObject = value;
		});
	};
	const stop = () => mediaStream.current?.getTracks().forEach(track => track.stop());
	const shot = () => {
		if (!videoRef.current) return;
		const canvas = document.createElement("canvas");
		const context = canvas.getContext("2d");
		context?.drawImage(videoRef.current, 0, 0, videoWidth * 2, videoHeight * 2);
		const url = canvas.toDataURL("image/png");
		setImgSrc(url);
	};
	const download = () => {
		const tagA = document.createElement("a");
		tagA.download = `${Date.now()}.png`;
		tagA.href = imgSrc;
		tagA.click();
	};
	const record = () => {
		if (!mediaStream.current) return;
		setReviewVideoSrc("");
		mediaRecorder.current = new MediaRecorder(mediaStream.current);
		mediaRecorder.current.ondataavailable = e => {
			videoChunks.current.push(e.data);
		};
		mediaRecorder.current.start();
	};
	const stopRecord = () => {
		mediaRecorder.current?.stop();
		const recorderFile = new Blob(videoChunks.current, { type: mediaRecorder.current?.mimeType });
		videoChunks.current = [];
		const file = new File([recorderFile], `${Date.now()}.mp4`, { type: "video/mp4" });
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onloadend = e => {
			if (typeof e.target?.result === "string") {
				setReviewVideoSrc(e.target?.result);
			}
		};
	};
	return (
		<div className="flex flex-col items-start">
			<video autoPlay ref={videoRef} width={videoWidth} height={videoHeight} />
			<Button type="primary" className="mt-2" onClick={launch}>
				打开摄像头
			</Button>
			<Button className="my-2" disabled={!mediaStream} onClick={stop}>
				关闭摄像头
			</Button>
			<div className="mb-2">
				<Button onClick={shot}>拍照</Button>
				<Button className="ml-2" onClick={download}>
					下载照片
				</Button>
				<Button type="primary" className="ml-2" onClick={record}>
					录像
				</Button>
				<Button type="primary" className="ml-2" onClick={stopRecord}>
					停止录像
				</Button>
			</div>
			{imgSrc && <img width={videoWidth} src={imgSrc} />}
			{reviewVideoSrc && <video controls width={videoWidth * 2} src={reviewVideoSrc} />}
		</div>
	);
};

export default CameraDemo;
